package fi.foyt.cs.persistence.dao.task;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.scene.SceneCategory;
import fi.foyt.cs.persistence.domainmodel.task.GeneralTaskLevel;
import fi.foyt.cs.persistence.domainmodel.task.GeneralTaskLevelCategory;

public class GeneralTaskLevelCategoryDAO extends GenericDAO<GeneralTaskLevelCategory> {
  
  public GeneralTaskLevelCategory create(Long generalTaskLevelId, SceneCategory category) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      GeneralTaskLevelCategory generalTaskLevelCategory = new GeneralTaskLevelCategory();
      generalTaskLevelCategory.setGeneralTaskLevelId(generalTaskLevelId);
      generalTaskLevelCategory.setSceneCategoryId(category.getId().getId());
      
      entityManager.persist(generalTaskLevelCategory);
      entityManager.getTransaction().commit();
      
      return generalTaskLevelCategory;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public GeneralTaskLevelCategory findByGeneralTaskLevelAndCategory(GeneralTaskLevel generalTaskLevel, SceneCategory category) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select g from GeneralTaskLevelCategory g where g.generalTaskLevelId = :generalTaskLevelId and g.sceneCategoryId = :sceneCategoryId");
    query.setParameter("generalTaskLevelId", generalTaskLevel.getId().getId());
    query.setParameter("sceneCategoryId", category.getId().getId());
    return getSingleResult(query);
  }
}
